<template>
  <div class="app-container">
    <!-- 表单部分 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <!-- 各个表单项 -->
      <el-form-item label="出库单编号" prop="outboundEntryId">
        <el-input
          v-model="pagin.search.outboundEntryId"
          placeholder="请输入出库单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库仓库" prop="warehouseId">
        <el-input
          v-model="pagin.search.warehouseId"
          placeholder="请输入仓库"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库类型" prop="outboundType">
        <el-select
          v-model="pagin.search.outboundType"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="type in outboundTypes"
            :key="type.value"
            :label="type.value"
            :value="type.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="approvalStatus">
        <el-select
          v-model="pagin.search.approvalStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in statusList"
            :key="dict.value"
            :label="dict.value"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDeleteAll"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格展示 -->
    <el-table
      v-loading="loading"
      :data="outboundList"
      @selection-change="handleSelectionChange"
      type="selection"
      show-row-hover
      selection-mode="multiple"
      header-cell-class-name="custom-checkbox-header"
    >
      <!-- 复选框列 -->
      <el-table-column type="selection" width="50"></el-table-column>
      <!-- 各列定义 -->
      <el-table-column
        prop="outboundEntryId"
        label="出库单编号"
      ></el-table-column>
      <el-table-column prop="outboundDate" label="出库日期"></el-table-column>
      <el-table-column prop="outboundType" label="出库类型"></el-table-column>
      <!-- <el-table-column prop="customerId" label="客户编号"></el-table-column> -->
      <el-table-column prop="warehouseName" label="出库仓库"></el-table-column>
      <el-table-column prop="outbounder" label="出库人"></el-table-column>
      <el-table-column prop="total" label="出库总数量"></el-table-column>
      <!-- <el-table-column prop="totalAmount" label="出库总金额"></el-table-column> -->
      <el-table-column prop="outboundNotes" label="出库备注"></el-table-column>
      <!-- <el-table-column prop="approverId" label="审批人编号"></el-table-column> -->
      <el-table-column prop="approvalDate" label="审批日期"></el-table-column>
      <el-table-column :formatter="orderStatusFormatter" label="状态"></el-table-column>
      
      <el-table-column
        label="操作"
        align="center"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="查询" placement="top">
            <el-button
              type="text"
              icon="Search"
              @click="handleSelectDetail(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button
              type="text"
              icon="Edit"
              @click="handleUpdateRow(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        class="pagiantion"
        @current-change="handleCurrentChange"
        :current-page="pagin.page"
        :page-size="pagin.count"
        layout="total, prev, pager, next, jumper"
        :total="pagin.total"
      >
      </el-pagination>
    </div>

    <!-- 添加或修改出库单对话框 -->
    <el-dialog :title="title" v-model="open" append-to-body v-if="open">
      <el-form
        ref="outboundRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 表单行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库单编号" prop="outboundEntryId">
              <el-input
                v-model="form.outboundEntryId"
                placeholder="请输入出库单编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库日期" prop="outboundDate">
              <el-date-picker
                v-model="form.outboundDate"
                type="date"
                placeholder="选择出库日期"
                :picker-options="{ firstDayOfWeek: 1 }"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库类型" prop="outboundType">
              <el-select
                v-model="form.outboundType"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="type in outboundTypes"
                  :key="type.value"
                  :label="type.value"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="customerId">
              <el-input
                v-model="form.customerId"
                placeholder="请输入客户编号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库编号" prop="warehouseId">
              <el-input
                v-model="form.warehouseId"
                placeholder="请输入出库编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库人" prop="outbounder">
              <el-input
                v-model="form.outbounder"
                placeholder="请输入出库人"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库总数量" prop="total">
              <el-input
                v-model="form.total"
                placeholder="请输入出库总数量"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库总金额" prop="totalAmount">
              <el-input
                v-model="form.totalAmount"
                placeholder="请输入出库总金额"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库备注" prop="outboundNotes">
              <el-input
                v-model="form.outboundNotes"
                placeholder="请输入出库备注"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批状态" prop="approvalStatus">
              <el-select
                v-model="form.approvalStatus"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="type in statusList"
                  :key="type.value"
                  :label="type.value"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审批人编号" prop="approverId">
              <el-input
                v-model="form.approverId"
                placeholder="请输入审批编号"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批日期" prop="approvalDate">
              <el-date-picker
                v-model="form.approvalDate"
                type="date"
                placeholder="选择审批日期"
                :picker-options="{ firstDayOfWeek: 1 }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm('outboundRef')"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--明细弹出框-->
    <el-dialog
      v-if="dialogVisible2"
      :title="title2"
      v-model="dialogVisible2"
      append-to-body
    >
      <!-- 表格展示 -->
      <el-table
      v-loading="loading"
      :data="whdetailedList"
      @selection-change="handleSelectionChange">
        <el-table-column
          prop="detailedId"
          label="产品明细编号"
        ></el-table-column>
        <!-- <el-table-column
          prop="warehousingId"
          label="出库单编号"
        ></el-table-column> -->
        <!-- <el-table-column prop="outBoundId" label="出库单编号"></el-table-column> -->
        <el-table-column
          prop="variantProductId"
          label="产品编号"
        ></el-table-column>
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <el-table-column prop="quantity" label="数量"></el-table-column>

        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <!-- <el-tooltip content="修改" placement="top">
              <el-button
                type="text"
                icon="Edit"
                @click="DetailUpdate(scope.row)"
              ></el-button>
            </el-tooltip> -->
            <el-tooltip content="删除" placement="top">
              <el-button
                type="text"
                icon="Delete"
                @click="handleDeleteDetail(scope.row.detailedId)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <div class="pagination-container">
        <el-pagination
          class="pagiantion"
          @current-change="handleChange"
          :current-page="queryParams.page"
          :page-size="queryParams.count"
          layout="total, prev, pager, next, jumper"
          :total="queryParams.total"
        >
        </el-pagination>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelThird">取 消</el-button>
          <!-- 如果需要确定按钮，可以添加 -->
          <!-- <el-button type="primary" @click="confirmThird">确 定</el-button> -->
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Outbound">
import {
  addOutbound,
  delOutbound,
  listOutbound,
  updateOutbound,
  // selectDetails
} from "@/api/reserve/outbound";
import { getCurrentInstance, reactive, ref } from "vue";

const { proxy } = getCurrentInstance();
const outboundList = ref([]);
const outboundDetailList = ref([]);
const status = ref([
  "待出库",
  "出库中",
  "已出库"
]);
const open = ref(false);
const openTwo = ref(false);
const openThird = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const title2 = ref("");
const titleTwo = ref("");
const titleThird = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);
const dialogVisible2 = ref(false);

// 添加一个响应式变量来存储选中的出库单记录
const selectedOutboundEntries = reactive([]);

const data = reactive({
  form: {
    outboundEntryId: null,
    outboundDate: null,
    outboundType: "销售出库",
    customerId: null,
    warehouseId: null,
    outbounder: null,
    total: null,
    totalAmount: null,
    outboundNotes: null,
    approvalStatus: "等待审批",
    approverId: null,
    approvalDate: null,
  },
  queryParams: {
    page: 1,
    total: 10,
    count: 5,
    search: {
      outboundEntryId: undefined,
      warehouseId: undefined,
      outboundType: undefined,
    },
  },
  statusList: [
    { value: "等待审批" },
    { value: "审批拒绝" },
    { value: "审批通过" },
    { value: "审批中" },
    { value: "已审批" },
  ],
  pagin: {
    page: 1,
    total: 10,
    count: 5,
    search: {
      outboundEntryId: undefined,
      warehouseId: undefined,
      outboundType: undefined,
      approvalStatus: undefined,
      outboundId: undefined

    },
  },
  rules: {
    outboundEntryId: [
      { required: true, message: "仓库不能为空", trigger: "blur" },
    ],
    outboundDate: [
      { required: true, message: "出库人不能为空", trigger: "blur" },
    ],
    outboundType: [
      { required: true, message: "审批人编号不能为空", trigger: "blur" },
    ],
    customerId: [
      { required: true, message: "审批状态不能为空", trigger: "change" },
    ],
    warehouseId: [
      { required: true, message: "出库日期不能为空", trigger: "blur" },
    ],
    outbounder: [
      { required: true, message: "出库类型不能为空", trigger: "change" },
    ],
    total: [{ required: true, message: "出库单编号不能为空", trigger: "blur" }],
    totalAmount: [
      { required: true, message: "出库总金额不能为空", trigger: "blur" },
    ],
    approvalStatus: [
      { required: true, message: "出库总数量不能为空", trigger: "blur" },
    ],
    approverId: [
      { required: true, message: "审批人编号不能为空", trigger: "blur" },
    ],
    approvalDate: [
      { required: true, message: "审批日期不能为空", trigger: "blur" },
    ],
  },
  outboundTypes: [
    { value: "销售出库" },
    { value: "调拨出库" },
    { value: "其他出库" },
    { value: "退货出库" },
    { value: "赠品出库" },
    { value: "维修出库" },
    { value: "损耗出库" },
    { value: "报废出库" },
  ],
  whdetailedList: [
    {
      detailedId: null,
      outboundId: null,
      variantProductId: null,
      productName: null,
      quantity: null,
      unitPrice: null,
      totalPrice: null,

    }
  ]
});



const { queryParams, statusList, form, rules, pagin, outboundTypes, whdetailedList } =
  toRefs(data);

// 查询出库单列表
function getList() {
  loading.value = true;
  listOutbound(pagin.value)
    .then((response) => {
      outboundList.value = response.list;
      pagin.value.page = response.current;
      pagin.value.total = response.total;
      loading.value = false;
    })
    .catch(() => {
      // 请求失败时将 pagin.page 传上去重新请求
      pagin.value.page = queryParams.page;
    });
}
// 切换页码
function handleCurrentChange(currentPage) {
  pagin.value.page = currentPage;
  getList();
}

// 取消按钮（查询明细时）
function cancelThird(){
  dialogVisible2.value = false;

}

// 切换页码（查询明细时）
function handleChange(currentPage) {
  queryParams.value.page = currentPage;
  handleSelectDetail(queryParams.value.search.outboundEntryId);
}


function handleSelectDetail(row) {
  title2.value = "查询出库明细";
  dialogVisible2.value = true;
  queryParams.value.search.outboundId = row.outboundEntryId;
  if (queryParams.value.page == null) {
    queryParams.value.page = 1;
  }
  getDetail();
}

function getDetail() {
  selectDetails(queryParams.value).then((response) => {
    whdetailedList.value = response.data.list;
    queryParams.value.total = response.data.total;
    console.log(whdetailedList);
    
  });
}

function orderStatusFormatter(row) {
  if (row.approvalStatus !== undefined && row.approvalStatus < status.value.length) {
    return status.value[row.approvalStatus];
  }
  return ""; // 或者返回一个默认值
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// function cancelThird() {
//   openThird.value = false;
//   queryParams.value.page = 1;
// }

function cancelTwo() {
  openTwo.value = false;
}

// 表单重置
function reset() {
  form.value = {
    approvalStatus: "等待审批",
    outboundDate: null,
    outboundType: null,
    warehouseId: null,
    outbounder: null,
    approverId: null,
  };
  proxy.resetForm("outboundRef");
}

// 搜索按钮操作
function handleQuery() {
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 新增出库单按钮操作
function handleAdd() {
  reset();
  data.form.isNew = true;
  open.value = true;
  title.value = "添加出库单";
}

// 查询出库明细按钮操作
// 修改 handleSelectDetail 方法，添加日志输出以便调试
// function handleSelectDetail(row) {
//   console.log("Selected row:", row);
//   queryParams.value.search.outboundEntryId = row.outboundEntryId;
//   loading.value = true;
//   selectDetails(queryParams.value)
//     .then((response) => {
//       outboundDetailList.value = response.data.records;
//       queryParams.value.page = response.data.page;
//       queryParams.value.total = response.data.total;
//       // 显示弹出框的逻辑，可以在这里添加一些条件判断或者直接显示弹出框
//       openThird.value = true;
//       titleThird.value = "查询出库明细";
//       loading.value = false;
//     })
//     .catch((error) => {
//       console.error("Error fetching details:", error);
//       loading.value = false;
//     });
// }

// 新增出库明细按钮操作
function handleAddDetail() {
  reset();
  openTwo.value = true;
  titleTwo.value = "添加出库明细单";
}

// 删除单个按钮操作
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.outboundEntryId + '"的数据项?')
    .then(function () {
      return delOutbound(row.outboundEntryId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      // 更新选中记录数组
      selectedOutboundEntries.splice(selectedOutboundEntries.indexOf(row), 1);
    })
    .catch(() => {});
    getList();
}

// 删除多个按钮操作
function handleDeleteAll() {
  const idsToDelete = selectedOutboundEntries.map(
    (item) => item.outboundEntryId
  );
  if (idsToDelete.length === 0) {
    proxy.$modal.msgWarning("请先选择要删除的出库单");
    return;
  }
  proxy.$modal
    .confirm("是否确认删除选中的 " + idsToDelete.length + " 个出库单数据项?")
    .then(function () {
      return Promise.all(idsToDelete.map((id) => delOutbound(id)));
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      // 清空选中记录数组
      selectedOutboundEntries.length = 0;
    })
    .catch(() => {});
    getList();
}

// 添加或修改按钮操作
function submitForm(formName) {
  if (formName === "outboundRef") {
    // 提交或修改出库单表单
    proxy.$refs.outboundRef.validate((valid) => {
      if (valid) {
        if (data.form.isNew) {
          // 新增出库单逻辑
          addOutbound(data.form)
            .then(() => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            })
            .catch((error) => {
              console.error("新增失败：", error);
              proxy.$modal.msgError("新增失败：" + error.message);
            });
        } else {
          // 修改出库单逻辑
          updateOutbound(data.form)
            .then(() => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            })
            .catch((error) => {
              console.error("修改失败：", error);
              proxy.$modal.msgError("修改失败：" + error.message);
            });
        }
      } else {
        console.error("表单验证不通过，请检查输入内容");
        proxy.$modal.msgError("表单验证不通过，请检查输入内容");
      }
    });
  }
}
// 修改单个行的操作
function handleUpdateRow(row) {
  // 将选中行的数据复制到表单中进行编辑
  form.value = { ...row };
  open.value = true;
  title.value = "修改出库单";
}

// 表格选中项变化处理函数（包括复选框和行选择）
function handleSelectionChange(selection) {
  selectedOutboundEntries.length = 0;
  selectedOutboundEntries.push(...selection);
}

// 全选复选框变化处理函数
function handleCheckboxAllChange(val) {
  outboundList.value.forEach((row) => {
    row.$selected = val;
  });
  if (val) {
    // 如果全选，将所有行添加到选中记录数组
    selectedOutboundEntries.length = 0;
    selectedOutboundEntries.push(...outboundList.value);
  } else {
    // 如果取消全选，清空选中记录数组
    selectedOutboundEntries.length = 0;
  }
}

getList();
</script>

<!-- <style>
  /* 自定义表头复选框样式（可选） */
.custom-checkbox-header.el-checkbox__input.is-checked +.el-checkbox__label {
    color: #409eff; /* 选中时字体颜色 */
  }

.custom-checkbox-header.el-checkbox__input.is-indeterminate +.el-checkbox__label {
    color: #409eff; /* 半选时字体颜色 */
  }
</style> -->
